package com.yhsoft.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhsoft.bill.service.ISysYszkService;
import com.yhsoft.common.response.PageResult;
import com.yhsoft.common.service.TokenService;
import com.yhsoft.common.utils.IDGenerator;
import com.yhsoft.common.vo.Result;
import com.yhsoft.sys.controller.Response.AdminAccountOutVo;
import com.yhsoft.sys.controller.Response.CompanyCountOutVo;
import com.yhsoft.sys.controller.Response.CompanySearchOutVo;
import com.yhsoft.sys.controller.Response.DistributorListOutVo;
import com.yhsoft.sys.controller.request.*;
import com.yhsoft.sys.entity.CompanyInfo;
import com.yhsoft.sys.entity.User;
import com.yhsoft.sys.service.ICompanyInfoService;
import com.yhsoft.sys.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 公司信息表 前端控制器
 * </p>
 *
 * @author yyyyyyyh
 * @since 2023-09-23
 */
@Api(tags = {"C-渠道商接口列表"})
@RestController
@RequestMapping("/companyInfo")
public class CompanyInfoController {

    @Autowired
    private ICompanyInfoService companyInfoService;

    @Autowired
    private IUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ISysYszkService iSysYszkService;

    @ApiOperation("数据统计")
    @GetMapping("/getCompanyCount")
    public Result<CompanySearchOutVo> getCompanyCount() {
        CompanySearchOutVo companySearchOutVo = companyInfoService.search();
        return Result.success(companySearchOutVo);
    }

    @ApiOperation("运营动态")
    @GetMapping("/getCount")
    public Result<CompanyCountOutVo> getCount() {
        CompanyCountOutVo count = companyInfoService.getCount();
        return Result.success(count);
    }

    @ApiOperation("新增/修改渠道商")
    @PostMapping("/addOrUpdateDistributor")
    public Result<?> addOrUpdateDistributor(@Valid @RequestBody DistributorInVo distributorInVo) {
        if (!StringUtils.hasLength(distributorInVo.getCompanyName()) || !StringUtils.hasLength(distributorInVo.getTrustLimit())) {
            return Result.fail("参数有误！单位名称和授信额度都不能为空！");
        }
        // 不能重复新增
        if (distributorInVo.getId() == null) {
            LambdaQueryWrapper<CompanyInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CompanyInfo::getCompanyName, distributorInVo.getCompanyName());
            List<CompanyInfo> companyInfoList = companyInfoService.list(wrapper);
            if (companyInfoList.size() > 0) {
                return Result.fail("渠道商已经存在，无法新增！");
            }
        }
        companyInfoService.addOrUpdateCompanyInfo(distributorInVo);

        // 增加应收账款记录
        LambdaQueryWrapper<CompanyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyInfo::getCompanyName, distributorInVo.getCompanyName());
        List<CompanyInfo> companyInfoList = companyInfoService.list(wrapper);
        if (companyInfoList.size() > 0) {
            Integer companyId = companyInfoList.get(0).getId();
            iSysYszkService.addYszk(companyId, distributorInVo.getTrustLimit());
        }
        return Result.success("成功!");
    }

    @ApiOperation("获取渠道商基本信息")
    @GetMapping("/getDistributorInfo")
    public Result<DistributorInVo> getDistributorInfo(@RequestParam(value = "distributorId") String distributorId) {
        DistributorInVo distributorInfo = new DistributorInVo();
        CompanyInfo companyInfo = companyInfoService.getBaseMapper().selectById(distributorId);
        BeanUtils.copyProperties(companyInfo, distributorInfo);
        return Result.success(distributorInfo);
    }

    @ApiOperation("获取企业基本信息")
    @GetMapping("/getCompanyInfo")
    public Result<DistributorInVo> getCompanyInfo() {
        Integer companyId = TokenService.getUserBytoken().getCompanyId();
        DistributorInVo distributorInfo = new DistributorInVo();
        CompanyInfo companyInfo = companyInfoService.getBaseMapper().selectById(companyId);
        if (companyInfo != null) {
            BeanUtils.copyProperties(companyInfo, distributorInfo);
        }
        return Result.success(distributorInfo);
    }

    @ApiOperation("分页查询渠道商")
    @GetMapping("/getAllDistributorList")
    public Result<PageResult<DistributorListOutVo>> getAllDistributorList(@RequestParam(value = "distributorName",
            required = false) String companyName,
                                                                          @RequestParam(value = "phone", required =
                                                                                  false) String contactsPhone,
                                                                          @RequestParam(value = "pageNo") Long pageNo,
                                                                          @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<CompanyInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyInfo::getIsDistributor, 1);
        wrapper.eq(StringUtils.hasLength(companyName), CompanyInfo::getCompanyName, companyName);
        wrapper.eq(StringUtils.hasLength(contactsPhone), CompanyInfo::getContactsPhone, contactsPhone);
        wrapper.orderByDesc(CompanyInfo::getId);

        Page<CompanyInfo> page = new Page<>(pageNo, pageSize);
        companyInfoService.page(page, wrapper);
        // List<DistributorListOutVo> data = page.getRecords().stream().map(DistributorListOutVo::valueOf).collect
        // (Collectors.toList());
        // return Result.success(new AllDistributorListInVo(page.getTotal(),data));
        return Result.success(PageResult.valueOf(page, DistributorListOutVo::valueOf));
    }

    @ApiOperation("删除渠道商")
    @PostMapping("/deleteDistributor")
    public Result<?> deleteDistributor(@RequestBody DeleteDistributorInVo ids) {
        companyInfoService.deleteDistributor(ids.getDistributorId());
        return Result.success("删除成功！");
    }

    @ApiOperation("设置渠道商状态（点击即修改）")
    @PostMapping("/setDistributorStatus")
    public Result<?> setDistributorStatus(@RequestParam(value = "id") Integer id) {
        companyInfoService.setDistributorStatus(id);
        return Result.success("设置成功！");
    }

    @ApiOperation("设置渠道商管理员账号")
    @PostMapping("/setDistributorAdmin")
    public Result<?> setDistributorAdmin(@RequestBody DistributorAdminInVo inVo) {
        // 判断是新增还是修改
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getCompanyId, inVo.getCompanyId())
                .eq(User::getIsAdmin, 1)
                .eq(User::getSysType, "saler");
        User adminUser = userService.getBaseMapper().selectOne(wrapper);
        if (adminUser == null) {
            //不能重复新增
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getUsername, inVo.getUsername());
            List<User> users = userService.list(queryWrapper);
            if (users.size() > 0) {
                return Result.fail("电话号码已经存在，无法新增！");
            }
            User user = new User();
            user.setId(IDGenerator.generate16("WebUser"));
            user.setCompanyId(inVo.getCompanyId());
            user.setUsername(inVo.getUsername());
            user.setPassword(passwordEncoder.encode(inVo.getPassword()));
            user.setAvatar("https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
            user.setIsAdmin(1);
            user.setRole("1");
            user.setDeleted(0);
            user.setSysType("saler");
            userService.addUser(user);
            return Result.success("新增管理员信息成功！");
        } else {
            adminUser.setUsername(inVo.getUsername());
            // 判断密码是否修改
            if (!inVo.getPassword().equals("********")) {
                adminUser.setPassword(passwordEncoder.encode(inVo.getPassword()));
            }
            userService.updateUser(adminUser);
            return Result.success("修改管理员信息成功！");
        }
    }

    @ApiOperation("查询渠道商管理员账号")
    @GetMapping("/getDistributorAdmin")
    public Result<AdminAccountOutVo> getDistributorAdmin(@RequestParam(value = "distributorId") Integer id) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getCompanyId, id)
                .eq(User::getIsAdmin, 1)
                .eq(User::getSysType, "saler");
        User adminUser = userService.getBaseMapper().selectOne(wrapper);
        AdminAccountOutVo adminAccountOutVo = new AdminAccountOutVo();
        if (!(adminUser == null)) {
            adminAccountOutVo.setAdminUserId(adminUser.getId());
            adminAccountOutVo.setUsername(adminUser.getUsername());
            adminAccountOutVo.setPassword("********");
        }
        return Result.success(adminAccountOutVo);
    }

    @ApiOperation("渠道商选择器")
    @GetMapping("/SalerSelector")
    public Result<List<CompanySelectorOutVo>> selector(@RequestParam(value = "distributorName", required = false) String companyName) {
        LambdaQueryWrapper<CompanyInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompanyInfo::getIsDistributor, 1);
        queryWrapper.like(StringUtils.hasLength(companyName), CompanyInfo::getCompanyName, companyName);
        List<CompanyInfo> list = companyInfoService.list(queryWrapper);
        List<CompanySelectorOutVo> outVoList = new ArrayList<>();
        if (list.size() > 0) {
            list.forEach(a -> {
                outVoList.add(new CompanySelectorOutVo(a.getId(), a.getCompanyName()));
            });
        }
        return Result.success(outVoList);
    }
}
